import logging, logging.config
import os
from configparser import RawConfigParser

BASE_DIRS = os.path.dirname(os.path.dirname(__file__))


def global_config_parser() -> RawConfigParser:
    _cp = RawConfigParser()
    if os.path.exists(os.path.join(BASE_DIRS, 'config.ini')):
        _cp.read(os.path.join(BASE_DIRS, 'config.ini'))
    else:
        _cp.read(os.path.join(BASE_DIRS, 'config.local.ini'))
    return _cp


def get_exchange_config(config_parser: RawConfigParser, exchange, key):
    return config_parser.get(f'quote:{exchange}', key, fallback=None)


LOG_BASE_DIRS = os.path.join(BASE_DIRS, 'logs')
if not os.path.exists(LOG_BASE_DIRS):
    os.makedirs(LOG_BASE_DIRS)


LOGING_CONFIG = {
    "version": 1,
    "formatters": {
        "default": {
            'format': '[%(asctime)s][%(filename)s.%(lineno)s][%(levelname).1s]: %(message)s',
        }
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "level": "INFO",
            "formatter": "default",
        },
        "web_handler": {
            "class": "logging.handlers.TimedRotatingFileHandler",
            "level": 'INFO',
            'when': 'D',
            'backupCount': 7,
            "filename": os.path.join(LOG_BASE_DIRS, 'web.log'),
            "formatter": "default",
        },
        "executor_handler": {
            "class": "logging.handlers.TimedRotatingFileHandler",
            "level": 'INFO',
            'when': 'D',
            'backupCount': 7,
            "filename": os.path.join(LOG_BASE_DIRS, 'executor.log'),
            "formatter": "default",
        },
        "scheduler_handler": {
            "class": "logging.handlers.TimedRotatingFileHandler",
            "level": 'INFO',
            'when': 'D',
            'backupCount': 7,
            "filename": os.path.join(LOG_BASE_DIRS, 'scheduler.log'),
            "formatter": "default",
        },
    },
    "loggers": {
        "web": {
            "handlers": ['web_handler'],
            "level": "INFO",
        },
        "executor": {
            "handlers": ['executor_handler'],
            "level": "INFO",
        },
        "scheduler": {
            "handlers": ['scheduler_handler'],
            "level": "INFO",
        },
        "root": {
            "handlers": ["console",],
            "level": "INFO",
        },
    },
}


def init_log():
    logging.config.dictConfig(LOGING_CONFIG)
